package com.hyg.lib_common.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSONArray;
import com.hyg.lib_base.MyView.BodyConstitutionPoint;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.DataModel.testting.DepressedData;
import com.hyg.lib_common.DataModel.testting.InsomniaData;
import com.hyg.lib_common.DataModel.testting.StressData;
import com.hyg.lib_common.DataModel.testting.TesttingAnswer;
import com.hyg.lib_common.DataModel.testting.TesttingXinliQuestion;
import com.hyg.lib_common.DataModel.testting.TypeAndScore;
import com.hyg.lib_common.R;
import com.hyg.lib_common.databinding.ActivityTestSelfTizhiBinding;
import com.hyg.lib_common.ui.adpter.RadioButtonAnswerAdapter;
import com.hyg.lib_common.ui.adpter.RadioButtonTizhiAdapter;
import com.hyg.lib_common.ui.adpter.RadioButtonTizhihorAdapter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class TestSelfTizhiActivity extends BaseActivity {
    ActivityTestSelfTizhiBinding binding;
    String type = "";
    ArrayList<TesttingXinliQuestion> list;
    String DataBaseDir = "testtingquestions";
    String questionData = "";

    public String result_main, result_vice;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityTestSelfTizhiBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        init();
    }

    public void init() {
        initData();
        initView();
    }


    public void initView() {
        StatusBarUtil.setStatusBar(1, this, getResources().getColor(R.color.white), 60, null, null, true);
        binding.lnTitleView.tvTitle.setText(type);
        binding.lnTitleView.tvTitleMore.setVisibility(View.VISIBLE);
        binding.lnTitleView.tvTitleMore.setText("问卷介绍");
        binding.tvQuestionNumber.setText(list.size() + "");
        binding.tvQuestionTime.setText((list.size() / 12 + 1) + "");

        binding.lnTitleView.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.lnTitleView.tvTitleMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TestSelfTizhiActivity.this, TesttingSelfIntroActivity.class);
                intent.putExtra("type", type);
                startActivity(intent);
            }
        });
        binding.btnFinishQuestion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<BodyConstitutionPoint> list=getResult();
                Intent intent=new Intent(TestSelfTizhiActivity.this,TestSelfTizhiResultActivity.class);
                intent.putExtra("main", result_main);
                intent.putExtra("vice",result_vice);
                intent.putExtra("type",type);
                intent.putParcelableArrayListExtra("list", list);
                startActivity(intent);
                finish();
            }
        });
        initRecycleView();
    }

    public void initRecycleView() {
        if (list == null) return;
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        binding.rcvQuestion.setLayoutManager(layoutManager);
        if (type.equalsIgnoreCase("体质辨识完整版")) {
            RadioButtonTizhihorAdapter adapter = new RadioButtonTizhihorAdapter(list, this);
            binding.rcvQuestion.setAdapter(adapter);
        } else {
            RadioButtonTizhiAdapter adapter = new RadioButtonTizhiAdapter(list, this);
            binding.rcvQuestion.setAdapter(adapter);
        }
    }

    public void initData() {
        type = getIntent().getStringExtra("type");
        list = new ArrayList<>();
        getQuestionList(type);
    }


    public void getQuestionList(String type) {
        String name = "";
        String questionData = "";
        switch (type) {
            case "体质辨识完整版":
                Log.i("lgb", "getQuestionList vtype==: " + type);
                if (true) {
                    name = "tizhi_male_1.0.0.json";
                } else {
                    name = "tizhi_female_1.0.0.json";
                }
                questionData = getQuestionData(name);
                list = parseQuestionList(questionData, 5);
                break;
            case "体质辨识简易版":
                name = "PhysiqueData_1.0.0.json";
                questionData = getQuestionData(name);
                list = parseQuestionList(questionData, 5);
                break;
        }
    }


    public String getQuestionData(String path) {
        questionData = "";
        try {
            AssetManager manager = getResources().getAssets();
            InputStream inputStream = manager.open(DataBaseDir + "/" + path);
            InputStreamReader isr = null;
            isr = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String length;
            while ((length = br.readLine()) != null) {
                sb.append(length + "\n");
            }
            br.close();
            isr.close();
            inputStream.close();
            questionData = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return questionData;
    }


    public ArrayList<TesttingXinliQuestion> parseQuestionList(String data, int mark) {
        ArrayList<TesttingXinliQuestion> list = new ArrayList<>();
        switch (mark) {
            case 2:
                ArrayList<StressData> list_StressData = (ArrayList<StressData>) JSONArray.parseArray(data, StressData.class);
                for (StressData stressData : list_StressData) {
                    list.add(new TesttingXinliQuestion(stressData.getQuestions(), stressData.getOption0(), stressData.getOption1()));
                }
                break;
            case 4:
                ArrayList<InsomniaData> list_InsomniaDatad = (ArrayList<InsomniaData>) JSONArray.parseArray(data, InsomniaData.class);
                for (InsomniaData insomniaData : list_InsomniaDatad) {
                    list.add(new TesttingXinliQuestion(insomniaData.getQuestions(), insomniaData.getOption0(), insomniaData.getOption1(), insomniaData.getOption2(), insomniaData.getOption3()));
                }
                break;
            case 5:
                ArrayList<DepressedData> list_Depressed = (ArrayList<DepressedData>) JSONArray.parseArray(data, DepressedData.class);
                for (DepressedData depressedData : list_Depressed) {
                    list.add(new TesttingXinliQuestion(depressedData.getQuestions(), depressedData.getOption0(), depressedData.getOption1(), depressedData.getOption2(), depressedData.getOption3(), depressedData.getOption4(), true, depressedData.getType()));
                }
                break;
        }
        return list;
    }


    public ArrayList<BodyConstitutionPoint> getResult() {
        int Score_Y = 10, Score_Q = 0, score_pinghe = 0;
        ArrayList<BodyConstitutionPoint> list_result = new ArrayList<>();

        ArrayList<TesttingXinliQuestion> arrayList = new ArrayList<>();
        int score_list = 0, real_score = 0;
        arrayList = getTypeList("气郁", list);
        score_list = calculateScoreTogether(arrayList, "气郁");
        real_score = calculateRealScoreTogether(score_list, arrayList.size());
        list_result.add(new BodyConstitutionPoint("气郁质", score_list, real_score, arrayList.size() + "", "气郁质"));

        arrayList = getTypeList("气虚", list);
        score_list = calculateScoreTogether(arrayList, "气虚");
        real_score = calculateRealScoreTogether(score_list, arrayList.size());
        list_result.add(new BodyConstitutionPoint("气虚质", score_list, real_score, arrayList.size() + "", "气虚质"));

        arrayList = getTypeList("阳虚", list);
        score_list = calculateScoreTogether(arrayList, "阳虚");
        real_score = calculateRealScoreTogether(score_list, arrayList.size());
        list_result.add(new BodyConstitutionPoint("阳虚质", score_list, real_score, arrayList.size() + "", "阳虚质"));

        arrayList = getTypeList("阴虚", list);
        score_list = calculateScoreTogether(arrayList, "阴虚");
        real_score = calculateRealScoreTogether(score_list, arrayList.size());
        list_result.add(new BodyConstitutionPoint("阴虚质", score_list, real_score, arrayList.size() + "", "阴虚质"));

        arrayList = getTypeList("痰湿", list);
        score_list = calculateScoreTogether(arrayList, "痰湿");
        real_score = calculateRealScoreTogether(score_list, arrayList.size());
        list_result.add(new BodyConstitutionPoint("痰湿质", score_list, real_score, arrayList.size() + "", "痰湿质"));

        arrayList = getTypeList("湿热", list);
        score_list = calculateScoreTogether(arrayList, "湿热");
        real_score = calculateRealScoreTogether(score_list, arrayList.size());
        list_result.add(new BodyConstitutionPoint("湿热质", score_list, real_score, arrayList.size() + "", "湿热质"));

        arrayList = getTypeList("血瘀", list);
        score_list = calculateScoreTogether(arrayList, "血瘀");
        real_score = calculateRealScoreTogether(score_list, arrayList.size());
        list_result.add(new BodyConstitutionPoint("血瘀质", score_list, real_score, arrayList.size() + "", "血瘀质"));

        arrayList = getTypeList("特禀", list);
        score_list = calculateScoreTogether(arrayList, "特禀");
        real_score = calculateRealScoreTogether(score_list, arrayList.size());
        list_result.add(new BodyConstitutionPoint("特禀质", score_list, real_score, arrayList.size() + "", "特禀质"));
        Collections.sort(list_result, new Comparator<BodyConstitutionPoint>() {
            @Override
            public int compare(BodyConstitutionPoint o1, BodyConstitutionPoint o2) {
                int i = (int) (o1.getConversionScore() - o2.getConversionScore());
                if (i == 0) {
                    return (int) (o1.getConversionScore() - o2.getConversionScore());
                }
                return -i;
            }
        });
        score_pinghe = calculateScoreTogether(getTypeList("平和", list), "平和");
        Score_Y = (int) list_result.get(0).getConversionScore();
        Score_Q = (int) list_result.get(1).getConversionScore();


        if (score_pinghe >= 60) {
            if (Score_Y < 30 && Score_Q < 30) {
                result_main = "平和";
                result_vice = "";
            } else if (Score_Y >= 40 && Score_Q >= 30) {
                result_main = list_result.get(0).getBodyConstitutionTypes();
                result_vice = list_result.get(1).getBodyConstitutionTypes();
            } else if (Score_Y < 40 && Score_Y >= 30 && Score_Q < 40) {
                result_main = "平和";
                result_vice = list_result.get(0).getBodyConstitutionTypes();
            } else if (Score_Y >= 40) {
                result_main = list_result.get(0).getBodyConstitutionTypes();
                result_vice = "";
            }
        } else {
            if (Score_Y < 30 && Score_Q < 30) {
                result_vice = "";
                result_main = (score_pinghe >= Score_Y && score_pinghe >= Score_Q) ? "平和" : (Score_Y >= Score_Q ? list_result.get(0).getBodyConstitutionTypes() : list_result.get(1).getBodyConstitutionTypes());
            } else if (Score_Y >= 40 && Score_Q >= 40) {
                result_main = list_result.get(0).getBodyConstitutionTypes();
                result_vice = list_result.get(1).getBodyConstitutionTypes();
            } else if (Score_Y >= 30 && Score_Q >= 30 && Score_Q < 40) {
                result_main = list_result.get(0).getBodyConstitutionTypes();
                result_vice = list_result.get(1).getBodyConstitutionTypes();
            } else if (Score_Y >= 30 && Score_Q < 30) {
                result_main = list_result.get(0).getBodyConstitutionTypes();
                result_vice = "";
            }
        }
        arrayList = getTypeList("平和", list);
        score_list = calculateScoreTogether(arrayList, "平和");
        real_score = calculateRealScoreTogether(score_list, arrayList.size());
        list_result.add(new BodyConstitutionPoint("平和质", score_list, real_score, arrayList.size() + "", "平和质"));
        return list_result;
    }


    /**
     * description:计算某个体质对应的一道选择题得分
     *
     * @param
     * @return
     * @author visitant
     * @time 2021/3/23 12:00
     */
    public int calculateScoreSingle(ArrayList<TesttingAnswer> list) {
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isChoose()) {
                sum = i + 1;
                return sum;
            }
        }
        return sum;
    }


    /**
     * description:计算某个体质对应的一道选择题得分
     *
     * @param isP 是否是平和体质
     * @return 一道选择题得分
     * @author visitant
     * @time 2021/3/23 11:59
     */
    public int calculateScoreSingle(ArrayList<TesttingAnswer> list, boolean isP) {
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isChoose()) {
                if (isP) {
                    sum = list.size() - i;
                } else {
                    sum = i + 1;
                }
                return sum;
            }
        }
        return sum;
    }


    /**
     * description:计算特定体质对应题库分值
     *
     * @return 某种体质最后得分
     * @author visitant
     * @time 2021/3/23 11:58
     */
    public int calculateScoreTogether(ArrayList<TesttingXinliQuestion> list, String type) {
        int sum = 0;
        for (int i = 0; i < list.size(); i++) {
            if (i != 0 && i != 5 && i != 6 && list.get(i).getType().contains("平和") && type.equalsIgnoreCase("平和")) {
                sum += calculateScoreSingle(list.get(i).getArrayList(), true);
            } else {
                sum += calculateScoreSingle(list.get(i).getArrayList());
            }
        }
        return sum;
    }


    /**
     * description:计算特定体质对应题库分值
     *
     * @return 某种体质最后得分
     * @author visitant
     * @time 2021/3/23 11:58
     */
    public int calculateRealScoreTogether(int sum, int size) {
        return (sum - size) * 25 / size;
    }


    /**
     * description: 获取某种体质对应题库
     *
     * @author visitant
     * @time 2021/3/23 11:57
     */
    public ArrayList<TesttingXinliQuestion> getTypeList(String type, ArrayList<TesttingXinliQuestion> list) {
        ArrayList<TesttingXinliQuestion> arrayList = new ArrayList<>();
        for (TesttingXinliQuestion question : list) {
            if (question.getType().contains(type)) {
                arrayList.add(question);
            }
        }
        return arrayList;
    }

}